package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class OrderLimitRoutePredicateFactory
        extends AbstractRoutePredicateFactory<OrderLimitRoutePredicateFactory.Config> {


    public OrderLimitRoutePredicateFactory() {
        //确保抛出的是OrderLimitRoutePredicateFactory里面的Config的class对象
        super(Config.class);
    }

    /**
     * - OrderLimit=1,10,1,100  需要截取1赋值给minPid，10赋值给maxPid,需要截取1赋值给minNum，100赋值给maxNum
     * ChangeLog : 1. 创建 (22/12/08/0008 16:44 [hlf]);
     *
     * @return java.util.List<java.lang.String>
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid","maxPid","minNum","maxNum");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String path = serverWebExchange.getRequest().getURI().getPath();

                String[] s = path.split("/");
                if(s.length != 4){
                    return false;
                }
                int pid = Integer.parseInt(s[s.length - 2]);
                int num = Integer.parseInt(s[s.length - 1]);

                if(pid<= config.getMaxPid() && pid >= config.getMinPid()
                        && num>= config.getMinNum() && num <= config.getMaxNum()){
                    return true;
                }else {
                    return false;
                }
            }
        };
    }
    /**
     * @Author: hlf
     * @Todo: 静态内部类：它和 写外面是一样的！
     * @Component: 成都蜗牛学苑
     **/
    @Validated
    public static class Config{
        int minPid;
        int maxPid;

        int minNum;
        int maxNum;

        public int getMinPid() {
            return minPid;
        }

        public void setMinPid(int minPid) {
            this.minPid = minPid;
        }

        public int getMaxPid() {
            return maxPid;
        }

        public void setMaxPid(int maxPid) {
            this.maxPid = maxPid;
        }

        public int getMinNum() {
            return minNum;
        }

        public void setMinNum(int minNum) {
            this.minNum = minNum;
        }

        public int getMaxNum() {
            return maxNum;
        }

        public void setMaxNum(int maxNum) {
            this.maxNum = maxNum;
        }
    }

}
